// JavaScript Document

function getContext(num){
	var values = new Array();
	for(var i=1;i<=num;i++){
		var temp = document.getElementById("solution_"+i).value;
		values[i-1]=temp;
	}
	return values;
}

function restoreContext(array){
	for(var i=1;i<=array.length;i++){
		
		document.getElementById("solution_"+i).value = array[i-1];
	}
}

function addSolution(){
	var numSol = document.getElementById("NUM_SOLUTION");
	var nextSolNum = parseFloat(numSol.value)+1;
	var pane = document.getElementById("solutionPane");
	var content = pane.innerHTML;
	var valueArray = getContext(numSol.value);
	var i=0;
	var count=0;
	var newContent = "";
	var nextSolText = "<div id=\""+nextSolNum+"\">" + nextSolNum + ". ";
	nextSolText = nextSolText +"<input type=\"text\" name=\"solution_" + nextSolNum + "\"  id=\"solution_" + nextSolNum + "\" />";
	nextSolText = nextSolText + "<img onclick=\"javascript:removeSolution('"+nextSolNum+"');\" src=\"images/remove-icon.png\"><br>";
	nextSolText = nextSolText +"</div>";
	for(i=1;i<content.length-4;i++){
		var str = content.substr(i,4);
		if(str == "<br>"){
			count++;
			if(count == numSol.value){
				newContent = content.substr(1,i+4);
				break;	
			}
		}
	}
	newContent = content.substr(1,i+9)+nextSolText+content.substr(i+10,content.length-(i+10));
	pane.innerHTML = newContent;
	document.getElementById("NUM_SOLUTION").value = nextSolNum;
	restoreContext(valueArray);
}

function removeSolution(num){
	var pane = document.getElementById("solutionPane");
	var solRef = document.getElementById("NUM_SOLUTION").value;
	var valueArray = getContext(solRef);	
	valueArray.splice(parseFloat(num)-1,1);
	for(var i=1;i<pane.childNodes.length;i++){
		if(pane.childNodes.item(i).tagName == "DIV"){
			if(pane.childNodes.item(i).id == num){
				var temp = pane.childNodes.item(i);
				pane.removeChild(temp);
			}
		}
	}
	var newContent = document.getElementById("solutionPane").innerHTML;
	for(var i=parseFloat(num)+1;i<=parseFloat(solRef);i++){
		var findc = i;
		var  replacec = i-1;
		var rg = new RegExp(findc,"gi");
		newContent = newContent.replace(rg,replacec);
	}
	pane.innerHTML = newContent;
	document.getElementById("NUM_SOLUTION").value = parseFloat(solRef)-1;
	restoreContext(valueArray);	
}



